package de.tsystems.dict.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.http.client.*;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;

import java.util.Date;

public class DictApplication implements EntryPoint {
    private static final String JSON_URL = "http://localhost:8080/dict-backend/";
    //GWT.getHostPageBaseURL();

    private static final int REFRESH_INTERVAL = 500; // ms

    private VerticalPanel mainPanel = new VerticalPanel();
    private FlexTable flexTable = new FlexTable();
    private HorizontalPanel addPanel = new HorizontalPanel();
    private TextBox newSymbolTextBox = new TextBox();
    private Button addLanguageButton = new Button("Add");
    private Label lastUpdatedLabel = new Label();
    private Label errorMsgLabel = new Label();


    /**
     * Entry point method.
     */
    public void onModuleLoad() {
        // Create table for stock data.
        flexTable.setText(0, 0, "Id");
        flexTable.setText(0, 1, "Name");
        flexTable.setText(0, 2, "Remove");

        // Add styles to elements in the stock list table.
        flexTable.setCellPadding(6);
        flexTable.getRowFormatter().addStyleName(0, "watchListHeader");
        flexTable.addStyleName("watchList");
        flexTable.getCellFormatter().addStyleName(0, 1, "watchListNumericColumn");
        flexTable.getCellFormatter().addStyleName(0, 2, "watchListRemoveColumn");

        // Assemble Add Language panel.
        addPanel.add(newSymbolTextBox);
        addPanel.add(addLanguageButton);
        addPanel.addStyleName("addPanel");

        // Assemble Main panel.
        errorMsgLabel.setStyleName("errorMessage");
        errorMsgLabel.setVisible(false);

        mainPanel.add(errorMsgLabel);
        mainPanel.add(flexTable);
        mainPanel.add(addPanel);
        mainPanel.add(lastUpdatedLabel);

        // Associate the Main panel with the HTML host page.
        RootPanel.get("wordList").add(mainPanel);

        // Move cursor focus to the input box.
        newSymbolTextBox.setFocus(true);

        // Setup timer to refresh list automatically.
//        Timer refreshTimer = new Timer() {
//            @Override
//            public void run() {
//                refreshLanguages();
//            }
//        };
//        refreshTimer.scheduleRepeating(REFRESH_INTERVAL);

        // Listen for mouse events on the Add button.
        addLanguageButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                addLanguage();
            }
        });

        // Listen for keyboard events in the input box.
        newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() {
            public void onKeyPress(KeyPressEvent event) {
                if (event.getCharCode() == KeyCodes.KEY_ENTER) {
                    addLanguage();
                }
            }
        });

        refreshLanguages();
    }

    /**
     * Add Language to FlexTable. Executed when the user clicks the addLanguageButton or
     * presses enter in the newSymbolTextBox.
     */
    private void addLanguage() {
        final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
        newSymbolTextBox.setFocus(true);

        // code must be between 1 and 10 chars that are numbers, letters, or dots.
//        if (!symbol.matches("^[0-9a-zA-Z\\.]{1,10}$")) {
//            Window.alert("'" + symbol + "' is not a valid symbol.");
//            newSymbolTextBox.selectAll();
//            return;
//        }
//        newSymbolTextBox.setText("");


        // REST add new Language
        createLanguage(symbol);

        // Add the stock to the table.
//        int row = flexTable.getRowCount();
//        flexTable.setText(row, 0, symbol);
//        flexTable.setWidget(row, 2, new Label());

//        flexTable.getCellFormatter().addStyleName(row, 0, "watchListNumericColumn");
//        flexTable.getCellFormatter().addStyleName(row, 1, "watchListNumericColumn");
//        flexTable.getCellFormatter().addStyleName(row, 2, "watchListRemoveColumn");

        // Add a button to remove this language from the table.
        Button removeButton = new Button("x");
        removeButton.addStyleDependentName("remove");
        removeButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                // TODO remove language REST
//                int removedIndex = words.indexOf(symbol);
//                words.remove(removedIndex);
//                flexTable.removeRow(removedIndex + 1);
            }
        });
        // add icon in Flex Table to remove row
        // flexTable.setWidget(row, 3, removeButton);


        // Get the stock price.
        // refreshLanguages();

    }


    private void createLanguage(String name) {

        final String url = URL.encode(JSON_URL + "api/languages/create");

        LanguageEntry language = (LanguageEntry) LanguageEntry.createObject();
        language.setName(name);

        JSONObject object = new JSONObject(language);

        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

        try {
            Request request = builder.sendRequest(null, new RequestCallback() {
                public void onError(Request request, Throwable exception) {
                    displayError("Couldn't retrieve JSON " + url);
                }

                public void onResponseReceived(Request request, Response response) {
                    if (200 == response.getStatusCode()) {
                        refreshLanguages();
                    } else {
                        displayError("Couldn't retrieve JSON (" + response.getStatusText()
                                + ")" + "URL: " + url);
                    }
                }
            });


        } catch (RequestException e) {
            displayError("Couldn't retrieve JSON " + url);
        }
    }


    private void refreshLanguages() {
        final String url = URL.encode(JSON_URL + "api/languages/list");

        // Send request to server and catch any errors.
        JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
        jsonp.setPredeterminedId("10");
//        jsonp.requestString(url, new AsyncCallback<String>() {
//            public void onFailure(Throwable caught) {
//                displayError(caught.getLocalizedMessage());
//            }
//
//            public void onSuccess(String result) {
//                displayError(result);
//            }
//        });
        jsonp.requestObject(url, new AsyncCallback<LanguageList>() {
            public void onFailure(Throwable caught) {
                displayError("Couldn't retrieve JSON " + url);
            }

            public void onSuccess(LanguageList languageList) {
                displayError(languageList.toSource());
                JsArray<LanguageEntry> entries = languageList.getLanguageEntries();
                updateTable(entries);
            }
        });
    }



    /**
     * Convert the string of JSON into JavaScript object.
     */
    private final native JsArray<LanguageEntry> asArrayOfLanguageData(String json) /*-{
        return eval(json);
    }-*/;

    /**
     * Update all table
     *
     * @param languages
     */
    private void updateTable(JsArray<LanguageEntry> languages) {


        for (int i = 0; i < languages.length(); i++) {
            updateTable(languages.get(i));
        }

        // Display timestamp showing last refresh.
        lastUpdatedLabel.setText("Last update : "
                + DateTimeFormat.getMediumDateTimeFormat().format(new Date()));

        // Clear any errors.
        errorMsgLabel.setVisible(false);
    }


    /**
     * Update a single row
     */
    private void updateTable(LanguageEntry languageData) {

        flexTable.setText(flexTable.getRowCount(), 1, languageData.getName());
    }

    /**
     * If can't get JSON, display error message.
     *
     * @param error
     */
    private void displayError(String error) {
        errorMsgLabel.setText("Error: " + error);
        errorMsgLabel.setVisible(true);
    }

}
